package com.trade.module.database.basic;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Desc: 数据源管理类（单例-线程安全）
 * @Version: v1.0 2017/12/6 10:39
 * @Author: zfb
 * @JDK Version: 1.8.0_51
 */
public class DataSourceManager {

    private Map<String,CustomDataSource> dataSourceMap = new HashMap<>();

    public static DataSourceManager instance;

    private DataSourceManager(){

    }

    public static DataSourceManager getInstance(){
        if(instance == null){
            instance = new DataSourceManager();
        }
        return instance;
    }

    /**
     * 获取数据源
     * @param driverName   驱动
     * @param dbUrl        url
     * @param userName     用户名
     * @param password     密码
     * @param connPollSize 连接池大小
     * @return CustomDataSource
     * @throws SQLException sql异常
     */
    public CustomDataSource getCustomDataSource(String driverName, String dbUrl, String userName, String password, int connPollSize) throws SQLException {
        CustomDataSource customDataSource;
        String dbPoolKey = dbUrl + "_" + userName + "_" + password;
        if(this.dataSourceMap.containsKey(dbPoolKey)) {
            customDataSource = this.dataSourceMap.get(dbPoolKey);
        } else {
            customDataSource = new CustomDataSource(driverName, dbUrl, userName, password, connPollSize);
            this.dataSourceMap.put(dbPoolKey, customDataSource);
        }
        return customDataSource;
    }

    /**
     * 删除数据源
     * @param dbUrl     url
     * @param userName  用户名
     * @param password  密码
     * @throws SQLException sql异常
     */
    public void removeDataSource(String dbUrl, String userName, String password) throws SQLException {
        String dbPoolKey = dbUrl + "_" + userName + "_" + password;
        if(this.dataSourceMap.containsKey(dbPoolKey)) {
            this.dataSourceMap.get(dbPoolKey).closeDataSource();
            this.dataSourceMap.remove(dbPoolKey);
        }

    }
}
